package com.vita.bduck.logger;

import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * 日志工厂实现类 ，用一个map保存多个Log
 */
public class AndroidLoggerFactory implements ILoggerFactory {
    private final Map<String, Log> loggerMap;

    static final int TAG_MAX_LENGTH = 23;
     // tag names cannot be longer on Android platform
    // see also android/system/core/include/cutils/property.h
    // and android/frameworks/base/core/jni/android_util_Log.cpp

    public AndroidLoggerFactory() {
        loggerMap = new HashMap<String, Log>();
    }


    public Log getLogger(final String name) {
        final String actualName = forceValidName(name);

        Log slog = null;
        // 防止并发访问loggerMap
        synchronized (this) {
            slog = loggerMap.get(actualName);
            if (slog == null) {
                if (!actualName.equals(name)) android.util.Log.i(LogConstant.LOG_TAG,
                        "Logger name '" + name + "' exceeds maximum length of " + TAG_MAX_LENGTH +
                                " characters, using '" + actualName + "' instead.");

                slog = new Log(actualName);
                loggerMap.put(actualName, slog);
            }
        }
        return slog;
    }

    /**
     * 修剪名字，防止超过TAG_MAX_LENGTH
     */
    private final String forceValidName(String name) {
        if (name != null && name.length() > TAG_MAX_LENGTH) {
            final StringTokenizer st = new StringTokenizer(name, ".");
            if (st.hasMoreTokens()) {
                final StringBuilder sb = new StringBuilder();
                String token;
                do {
                    token = st.nextToken();
                    if (token.length() == 1) {
                        sb.append(token);
                        sb.append('.');
                    } else if (st.hasMoreTokens()) {
                        sb.append(token.charAt(0));
                        sb.append("*.");
                    } else {
                        sb.append(token);
                    }
                } while (st.hasMoreTokens());

                name = sb.toString();
            }
            if (name.length() > TAG_MAX_LENGTH) {
                name = name.substring(0, TAG_MAX_LENGTH - 1) + '*';
            }
        }
        return name;
    }
}
